//
//  LYPersonalEnumView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/8/1.
//

import UIKit
import SnapKit

class LYPersonalEnumView: UIView {
    
    // MARK: - 公开属性
    var selectedIndex: Int = -1 {
        didSet {
            updateButtonSelection()
        }
    }
    
    var dataSource: [Phasbook] = [] {
        didSet {
            setupButtons()
        }
    }
    
    var currentPhasbook: Phasbook? = nil
    
    var onSelectionChanged: ((Int, Phasbook?) -> Void)?
    var onConfirmaAction: ((Phasbook?) -> Void)?
    // MARK: - 私有属性
    private let scrollView = UIScrollView()
    private let stackView = UIStackView()
    private var buttons: [EnumButton] = []
    
    private lazy var confirmButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle(LYlocalizedString("Confirm"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = .systemBlue
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 22
        button.addTarget(self, action: #selector(confirmSelection(_:)), for: .touchUpInside)
        return button
    }()
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - UI设置
    private func setupUI() {
        // 滚动视图
        scrollView.showsVerticalScrollIndicator = false
        addSubview(scrollView)
        
        // 堆栈视图
        stackView.axis = .vertical
        stackView.alignment = .fill
        stackView.spacing = 12
        scrollView.addSubview(stackView)
        addSubview(confirmButton)
        
        // 约束
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(90)
            make.bottom.equalTo(confirmButton.snp.top)
        }
        
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        confirmButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(45)
            make.bottom.equalToSuperview().offset(-15)
        }
    }
    
    private func setupButtons() {
        // 清除旧按钮
        buttons.forEach { $0.removeFromSuperview() }
        buttons.removeAll()
        
        // 创建新按钮（使用Phasbook模型的sarcling字段作为标题）
        for (index, item) in dataSource.enumerated() {
            let button = createButton(title: item.sarcling ?? "未命名", tag: index)
            buttons.append(button)
            stackView.addArrangedSubview(button)
        }
        
        updateButtonSelection()
    }
    
    private func createButton(title: String, tag: Int) -> EnumButton {
        let button = EnumButton(type: .custom)
        button.tag = tag
        button.nameLabel.text = title
//        button.setTitle(title, for: .normal)
//        button.setTitleColor(.darkGray, for: .normal)
//        button.setTitleColor(.white, for: .selected)
//        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = .clear
//        button.layer.cornerRadius = 8
//        button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 16, bottom: 12, right: 16)
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
        return button
    }
    
    private func updateButtonSelection() {
        for (index, button) in buttons.enumerated() {
            button.isSelected = index == selectedIndex
            button.nameView.backgroundColor = button.isSelected ? UIColor(hex: "#FFEEC5") : .clear
        }
    }
    
    // MARK: - 按钮点击事件
    @objc private func buttonTapped(_ sender: EnumButton) {
        selectedIndex = sender.tag
        let selectedItem = dataSource[safe: selectedIndex]
        self.currentPhasbook = selectedItem
        onSelectionChanged?(selectedIndex, selectedItem)
    }
    
    @objc func confirmSelection(_ sender: UIButton) {
        onConfirmaAction?(self.currentPhasbook)
    }
    
    // MARK: - 公开方法
    func selectItem(at index: Int, animated: Bool = false) {
        guard index >= 0 && index < dataSource.count else { return }
        selectedIndex = index
        
        if animated {
            UIView.animate(withDuration: 0.3) {
                self.updateButtonSelection()
            }
        }
        
        // 滚动到选中按钮
        if index < buttons.count {
            let button = buttons[index]
            scrollView.scrollRectToVisible(button.frame, animated: animated)
        }
    }
}

class EnumButton: UIButton {
    
    let nameView = UIView()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .center
        label.textColor = UIColor(hex: "#000000")
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        nameView.isUserInteractionEnabled = false
        nameView.layer.masksToBounds = true
        nameView.layer.cornerRadius = 15
        addSubview(nameView)
        addSubview(nameLabel)
        
        nameLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(30)
        }
        
        nameView.snp.makeConstraints { make in
            make.top.bottom.equalTo(nameLabel)
            make.leading.equalTo(nameLabel).offset(-12)
            make.trailing.equalTo(nameLabel).offset(12)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// 数组安全访问扩展
extension Array {
    subscript(safe index: Int) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
